package com.hqd.ch03.v28.tx.transaction.interceptor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class RuleBasedTransactionAttribute extends DefaultTransactionAttribute implements Serializable {

    public static final String PREFIX_ROLLBACK_RULE = "-";
    public static final String PREFIX_COMMIT_RULE = "+";


    private List<RollbackRuleAttribute> rollbackRules;

    public RuleBasedTransactionAttribute() {
        super();
    }

    public RuleBasedTransactionAttribute(RuleBasedTransactionAttribute other) {
        super(other);
        this.rollbackRules = (other.rollbackRules != null ? new ArrayList<>(other.rollbackRules) : null);
    }

    public RuleBasedTransactionAttribute(int propagationBehavior, List<RollbackRuleAttribute> rollbackRules) {
        super(propagationBehavior);
        this.rollbackRules = rollbackRules;
    }

    public List<RollbackRuleAttribute> getRollbackRules() {
        if (this.rollbackRules == null) {
            this.rollbackRules = new ArrayList<>();
        }
        return this.rollbackRules;
    }

    public void setRollbackRules(List<RollbackRuleAttribute> rollbackRules) {
        this.rollbackRules = rollbackRules;
    }

    @Override
    public boolean rollbackOn(Throwable ex) {
        RollbackRuleAttribute winner = null;
        int deepest = Integer.MAX_VALUE;

        if (this.rollbackRules != null) {
            for (RollbackRuleAttribute rule : this.rollbackRules) {
                int depth = rule.getDepth(ex);
                if (depth >= 0 && depth < deepest) {
                    deepest = depth;
                    winner = rule;
                }
            }
        }

        if (winner == null) {
            return super.rollbackOn(ex);
        }

        return !(winner instanceof NoRollbackRuleAttribute);
    }

}